$(function(){
    layui.use(['locals','table','layer','util'],function(){
        var locals = layui.locals;
        var table = layui.table;
        var layer = layui.layer;
        var util = layui.util;
        var pageName = getPageName();
        let allArea = [];
        var devTypeObj = {
            1: {name: '水', unit:'T', img: 'meter-water.png'},
            0: {name: '电', unit:'kW·h', img: 'meter-electronic.png'}
        };
        var localParam = locals.get(pageName);
        let selParam = {
          area: '0',
          type:   '0'
        };
        let myChart = null;
        var interval = 1000 * 60 * 60 ;  // 页面刷新频率 1000 * 60 * 60 = 1h
        var timer = null; // 页面定时器
        let counter = 0; // 已刷新次数
        let layerNum = 0; // 已打开的layer数量
        let currentTimeType = locals.get('currentTimeType') === null ? 0 : locals.get('currentTimeType');
        var query = getQuery();
        if(localParam){
            selParam = localParam;
        }
        $('.functional select.areaSel option[value="' + selParam.area + '"]').prop('selected',true);
        $('em.typeName').text(devTypeObj[selParam.type].name);
        if(selParam.type == '0'){
            $('.icon-border').addClass('dian');
            $('.icon-border').removeClass('shui');
            $('.icon-border i.icon-shui').addClass('layui-hide');
            $('.icon-border i.icon-dian').removeClass('layui-hide');
        }else{
            $('.icon-border').addClass('shui');
            $('.icon-border').removeClass('dian');
            $('.icon-border i.icon-dian').addClass('layui-hide');
            $('.icon-border i.icon-shui').removeClass('layui-hide');
        }
        $('.functional .meter-btn').removeClass('btn-selected');
        $('.functional .meter-btn[deviceTypeCode="' + selParam.type + '"]').addClass('btn-selected');

        function getQuery() {
            // 切分链接上的参数
            var str = decodeURI(window.location.search.split("?")[1]);
            //如果链接上没有，就不往下执行了
            if (str === 'undefined'){
                return
            }else{
                return str
            };
        }

        getAreaData();
        getDatas(selParam);

        $('.functional select.areaSel').on('change',function () {
            selParam.area = $(this).val()
            areaId = $(this).val();
            // window.location.href = "/monitor/index.do?areaId=" + $(this).val() + '&type=' + devType;
            $('.functional select.areaSel option[value="' + selParam.area + '"]').prop('selected',true);
            // 缓存所选区域
            locals.set(pageName, selParam);
            getDatas(selParam);
        });

        // 监听水电表切换
        $('.functional .meter-btn').on('click',function () {
            selParam.type = $(this).attr('deviceTypeCode');
            $('em.typeName').text(devTypeObj[selParam.type].name);
            $('.functional .meter-btn').removeClass('btn-selected');
            $('.functional .meter-btn[deviceTypeCode="' + selParam.type + '"]').addClass('btn-selected');
            if(selParam.type == '0'){
                $('.icon-border').addClass('dian');
                $('.icon-border').removeClass('shui');
                $('.icon-border i.icon-shui').addClass('layui-hide');
                $('.icon-border i.icon-dian').removeClass('layui-hide');
            }else{
                $('.icon-border').addClass('shui');
                $('.icon-border').removeClass('dian');
                $('.icon-border i.icon-dian').addClass('layui-hide');
                $('.icon-border i.icon-shui').removeClass('layui-hide');
            }
            myChart.clear();
            locals.set(pageName, selParam);
            getDatas(selParam);
        });

        function getDatas(obj){
            $.ajax({
                type: "post",
                url: ctx + "/monitor/getRealTimeFlow.do",
                data: {
                    areaId: obj.area || '0',
                    deviceTypeCode: obj.type || '0'
                },
                dataType: "json",
                success: function (res) {
                    if (res.code == "000000") {
                        locals.set(pageName, selParam);
                        let data = res.data;
                        // 概括
                        let curArea = $('.functional > select.areaSel option:selected').text();
                        $('.title-part em.areaName').text(curArea);
                        $('.title-part .date').text(data.date);
                        $('.count-part .totalCnt').text(data.total);
                        $('.count-part .ratecCnt').text((parseFloat(data.rate) * 100).toFixed(1) + '%');
                        $('.count-part .totalUse').text(data.totalQuantiry);
                        $('.count-part .standardUse').text(data.standardQuantiry);
                        $('.count-part .standardUse1').text(data.standardQuantiry1);
                        $('.count-part em.unit').text(devTypeObj[selParam.type].unit);
                        if(data.rate < 0){
                            $('.count-part .ratecCnt').addClass('fontRed');
                        }else {
                            $('.count-part .ratecCnt').removeClass('fontRed');
                        }
                        // 报警信息
                        $('.alert-list ul').empty();
                        let alertList = '';
                        if(data.offlines + data.overflows === 0){
                            alertList = '<li style="color: #fff">无异常报警</li>'
                        }else{
                            let idx = data.offlines;
                            for (let k in data.offline){
                                alertList += `<li>[${k}] ${data.offline[k]}离线</li>`;
                            }
                            for (let k in data.overflow){
                                alertList += `<li>[${idx + parseInt(k)}] ${data.overflow[k]}超标</li>`;
                            }
                        }
                        $('.alert-list ul').append(alertList);

                        // 水表list
                        renderMeterList(data.list);

                        // 3d
                        let chartData = {
                            totalCnt: data.total,
                            overCnt: data.overflows,
                            offCnt: data.offlines,
                            normalCnt: data.total - data.overflows,
                        };
                        chart3D(chartData);
                    } else {
                        console.error(res.message);
                    }
                }
            });
        }

        // 获取全部区域
        function getAreaData() {
            $.ajax({
                type: "post",
                url: ctx + "/areaManger/areaAll.do",
                data: {},
                dataType: "json",
                success: function (res) {
                    $('.functional > select.areaSel').empty();
                    allArea = [].concat(res);
                    let opt = '<option value="0">全部区域</option>';
                    for (let i = 0; i < allArea.length; i++) {
                        opt += `<option value="${allArea[i].areaId}">${allArea[i].areaName}区域</option>`;
                    }
                    $('.functional > select.areaSel').append(opt);

                    $('.functional select.areaSel option[value="' + selParam.area + '"]').prop('selected',true);
                    // figureParam(localParam, query);
                }
            });
        }

        // 水表展示
        function renderMeterList(list){
            $('.right-part').empty();
            let html = '';
            if(list.length === 0){
                html += '<div style="margin: 50px auto;"><h3>该区域暂无仪表</h3></div>'
            }else{
                for (let i = 0; i < list.length; i++) {
                    let item = list[i];
                    let mName = item.anotherName;
                    let bgc = item.overExceedFlow ? 'bgRed' : item.isNA == 'N/A' ? 'bgGray' : 'bgBlue';
                    let currentQuantity = item.isNA == 'N/A' ? item.isNA : item.currentQuantity; // decimalNum(item.currentQuantity);
                    html += `<div class="sigle-item" meterCode="${item.meterCode}" areaId="${item.areaId}" mName="${mName}">
                            <h4 title="${mName}">${mName}</h4>
                            <p>日累计<span class="quantity ${bgc}"><em>${item.intervalQuantity == null ? 'N/A' : item.intervalQuantity}</em> / <em>${item.cumulativeStandard == null ? '' : item.cumulativeStandard}</em></span><span class="unit">${devTypeObj[selParam.type].unit}</span></p>
                            <div class="meter-img" devtype="${selParam.type}">
                                <img src="/statics/imgs/${devTypeObj[selParam.type].img}" alt="">
                                <span>${currentQuantity}</span>
                            </div>
                        </div>`;
                }
            }

            $('.right-part').append(html);
        }

        let mCodeArr = [];
        $('body').on('click','.sigle-item',function () {
            let _this = $(this);
            let mCode = $(this).attr('meterCode');
            // 已有弹窗 不再弹出
            if(mCodeArr.indexOf(mCode) === -1){
                let today = util.toDateString(new Date(), 'yyyy-MM-dd');
                locals.set('waterChart', {
                    area: [$(this).attr('areaId')],
                    repType: "2",
                    chartType: 'lineTrend',
                    deviceTypeCode: selParam.type,
                    meter: [mCode],
                    dateObj: {
                        2: defaultSTimeETime(currentTimeType,'2'),
                        3: defaultSTimeETime(currentTimeType,'3'),
                        4: defaultSTimeETime(currentTimeType,'4'),
                        5: defaultSTimeETime(currentTimeType,'5')
                    }
                });

                layer.open({
                    type: 2,
                    title: '&nbsp;',
                    // title: $(this).attr('areaId') + ' / ' + $(this).attr('meterCode') + ' / ' + $(this).attr('mName'),
                    closeBtn: 1,
                    shade: 0,
                    anim: 0,
                    area: ['60%', '60%'],
                    maxmin: true,
                    content: ['/waterChart/waterChartIndex.do', 'no'],
                    success: function(layero, index) {
                        layerNum++;
                        let body = layer.getChildFrame('body', index);
                        body.find('.layui-header').addClass('layui-hide');
                        body.find('.layui-side').addClass('layui-hide');
                        body.find('.layui-body').css({top: 0, left: 0});
                        body.find('.layui-body').addClass('iframe-layer');
                    },
                    end: function(){
                        // 弹窗关闭，数量-1
                        layerNum--;
                    },
                    cancel: function(index, layero){
                        let idx = mCodeArr.indexOf(mCode);
                        mCodeArr.splice(idx, 1);
                        layer.close(index);
                        return false;
                    }
                });
            }
            if(mCodeArr.indexOf(mCode) === -1){
                mCodeArr.push(mCode);
            }
        });

        // 3d 圆环图
        function chart3D(chartData) {
            /*************************
             pie3D 尝试
             更新时间: 2020.10.8 17:12 v1.1
             使用组件: grid3D、xAxis3D、yAxis3D、zAxis3D、surface
             EC 版本: 4.8.0
             GL 版本：0.4.3
             根据用户ZhXand618的模板克隆
             如果转载: 请注明出处
             *************************
             【 getParametricEquation 函数说明 】 :
             *************************
             根据传入的
             startRatio（浮点数）: 当前扇形起始比例，取值区间 [0, endRatio)
             endRatio（浮点数）: 当前扇形结束比例，取值区间 (startRatio, 1]
             isSelected（布尔值）:是否选中，效果参照二维饼图选中效果（单选）
             isHovered（布尔值）: 是否放大，效果接近二维饼图高亮（放大）效果（未能实现阴影）
             k（0~1之间的浮点数）：用于参数方程的一个参数，取值 0~1 之间，通过「内径/外径」的值换算而来。

             生成 3D 扇形环曲面
             *************************
             【 getPie3D 函数说明 】 :
             *************************
             根据传入的
             pieData（object）：饼图数据
             internalDiameterRatio（0~1之间的浮点数）：内径/外径的值（默认值 1/2），当该值等于 0 时，为普通饼图
             生成模拟 3D 饼图的配置项 option
             备注：饼图数据格式示意如下
             [{
                name: '数据1',
                value: 10
            }, {
                // 数据项名称
                name: '数据2',
                value : 56,
                itemStyle:{
                    // 透明度
                    opacity: 0.5,
                    // 扇形颜色
                    color: 'green'
                }
            }]

             *************************/

            // 生成扇形的曲面参数方程，用于 series-surface.parametricEquation
            function getParametricEquation(startRatio, endRatio, isSelected, isHovered, k, h) {

                // 计算
                let midRatio = (startRatio + endRatio) / 2;

                let startRadian = startRatio * Math.PI * 2;
                let endRadian = endRatio * Math.PI * 2;
                let midRadian = midRatio * Math.PI * 2;

                // 如果只有一个扇形，则不实现选中效果。
                if (startRatio === 0 && endRatio === 1) {
                    isSelected = false;
                }

                // 通过扇形内径/外径的值，换算出辅助参数 k（默认值 1/3）
                k = typeof k !== 'undefined' ? k : 1 / 3;

                // 计算选中效果分别在 x 轴、y 轴方向上的位移（未选中，则位移均为 0）
                let offsetX = isSelected ? Math.cos(midRadian) * 0.1 : 0;
                let offsetY = isSelected ? Math.sin(midRadian) * 0.1 : 0;

                // 计算高亮效果的放大比例（未高亮，则比例为 1）
                let hoverRate = isHovered ? 1.05 : 1;

                // 返回曲面参数方程
                return {
                    u: {
                        min: -Math.PI,
                        max: Math.PI * 3,
                        step: Math.PI / 32
                    },
                    v: {
                        min: 0,
                        max: Math.PI * 2,
                        step: Math.PI / 20
                    },
                    x: function(u, v) {
                        if (u < startRadian) {
                            return offsetX + Math.cos(startRadian) * (1 + Math.cos(v) * k) * hoverRate;
                        }
                        if (u > endRadian) {
                            return offsetX + Math.cos(endRadian) * (1 + Math.cos(v) * k) * hoverRate;
                        }
                        return offsetX + Math.cos(u) * (1 + Math.cos(v) * k) * hoverRate;
                    },
                    y: function(u, v) {
                        if (u < startRadian) {
                            return offsetY + Math.sin(startRadian) * (1 + Math.cos(v) * k) * hoverRate;
                        }
                        if (u > endRadian) {
                            return offsetY + Math.sin(endRadian) * (1 + Math.cos(v) * k) * hoverRate;
                        }
                        return offsetY + Math.sin(u) * (1 + Math.cos(v) * k) * hoverRate;
                    },
                    z: function(u, v) {
                        if (u < -Math.PI * 0.5) {
                            return Math.sin(u);
                        }
                        if (u > Math.PI * 2.5) {
                            return Math.sin(u) * h * .1;
                        }
                        return Math.sin(v) > 0 ? 1 * h * .1 : -1;
                    }
                };
            }

            // 生成模拟 3D 饼图的配置项
            function getPie3D(pieData, internalDiameterRatio) {
                let series = [];
                let sumValue = 0;
                let startValue = 0;
                let endValue = 0;
                let legendData = [];
                let k = typeof internalDiameterRatio !== 'undefined' ? (1 - internalDiameterRatio) / (1 + internalDiameterRatio) : 1 / 3;

                // 为每一个饼图数据，生成一个 series-surface 配置
                for (let i = 0; i < pieData.length; i++) {
                    sumValue += pieData[i].value;
                    let seriesItem = {
                        name: typeof pieData[i].name === 'undefined' ? `series${i}` : pieData[i].name,
                        type: 'surface',
                        parametric: true,
                        wireframe: {
                            show: false
                        },
                        pieData: pieData[i],
                        pieStatus: {
                            selected: false,
                            hovered: false,
                            k: k
                        }
                    };

                    if (typeof pieData[i].itemStyle != 'undefined') {
                        let itemStyle = {};
                        typeof pieData[i].itemStyle.color != 'undefined' ? itemStyle.color = pieData[i].itemStyle.color : null;
                        typeof pieData[i].itemStyle.opacity != 'undefined' ? itemStyle.opacity = pieData[i].itemStyle.opacity : null;

                        seriesItem.itemStyle = itemStyle;
                    }
                    series.push(seriesItem);
                }

                // 使用上一次遍历时，计算出的数据和 sumValue，调用 getParametricEquation 函数，
                // 向每个 series-surface 传入不同的参数方程 series-surface.parametricEquation，也就是实现每一个扇形。
                for (let i = 0; i < series.length; i++) {
                    endValue = startValue + series[i].pieData.value;
                    series[i].pieData.startRatio = startValue / sumValue;
                    series[i].pieData.endRatio = endValue / sumValue;
                    series[i].parametricEquation = getParametricEquation(series[i].pieData.startRatio, series[i].pieData.endRatio, false, false, k, series[i].pieData.value);
                    startValue = endValue;
                    legendData.push(series[i].name);
                }

                // 补充一个透明的圆环，用于支撑高亮功能的近似实现。
                series.push({
                    name: 'mouseoutSeries',
                    type: 'surface',
                    parametric: true,
                    wireframe: {
                        show: false
                    },
                    itemStyle: {
                        opacity: 0
                    },
                    parametricEquation: {
                        u: {
                            min: 0,
                            max: Math.PI * 2,
                            step: Math.PI / 20
                        },
                        v: {
                            min: 0,
                            max: Math.PI,
                            step: Math.PI / 20
                        },
                        x: function(u, v) {
                            return Math.sin(v) * Math.sin(u) + Math.sin(u);
                        },
                        y: function(u, v) {
                            return Math.sin(v) * Math.cos(u) + Math.cos(u);
                        },
                        z: function(u, v) {
                            return Math.cos(v) > 0 ? 0.1 : -0.1;
                        }
                    }
                });

                // 准备待返回的配置项，把准备好的 legendData、series 传入。
                let option = {
                    // animation: true,
                    title: {
                        text: chartData.overCnt + '\n超标',
                        x: 'center',
                        y: 'center',
                        textStyle: {
                            fontSize: 16,
                            color: '#fff',
                            fontWeight: 'normal'
                        }
                    },
                    xAxis3D: {
                        min: -1,
                        max: 1
                    },
                    yAxis3D: {
                        min: -1,
                        max: 1
                    },
                    zAxis3D: {
                        min: -1,
                        max: 1
                    },
                    grid3D: {
                        show: false,
                        boxHeight: 30,
                        bottom: 10,
                        viewControl: {//3d效果可以放大、旋转等，参考官方配置
                            alpha: 45,
                            distance: 200,
                            rotateSensitivity: 0,
                            zoomSensitivity: 0,
                            panSensitivity: 0,
                            autoRotate: true
                        }
                    },
                    series: series
                };
                return option;
            }

            // 传入数据生成 option
            myChart = echarts.init(document.getElementById('gl-pie'), 'darkTheme');
            var option = getPie3D([{
                name: '正常',
                value: chartData.normalCnt,
                itemStyle: {
                    opacity: .8,
                    color: 'rgba(0, 149, 227, 1)'
                }
            },{
                name: '超标',
                value: chartData.overCnt,
                itemStyle: {
                    opacity: .8,
                    color: 'rgba(255,36,39,1)'
                }
            },{
                name: '离线',
                value: chartData.offCnt,
                itemStyle: {
                    opacity: .8,
                    color: 'rgba(102,102,102,1)'
                }
            }], 0.5);
            myChart.setOption(option);
        }

        // 页面刷新
        // if(timer){
        //     clearTimeout(timer);
        //     timer = null;
        // }
        // timer = setInterval(function () {
        //     // window.location.reload();
        //     getDatas(selParam)
        // }, interval);
        function refreshPage(){
            if (counter > 0 && counter % 12 === 0) {  // 刷到12次就重载页面
                if(layerNum == 0){
                    window.location.reload();
                }
            }
            if (timer) {
                clearTimeout(timer);
                timer = null;
            }
            timer = setTimeout(() => {
                getDatas(selParam);
                refreshPage();
                counter++;
            }, interval);
        }
        refreshPage();
        /**
         * stepLength：一次滚动步长
         * speed：滚动速度
         * delay：停留时间
         * element：Element对象
         *
         * element.offsetHeight 元素的像素高度（包括边框和填充）
         * element.scrollTop 元素的内容垂直滚动的像素
         * element.scrollHeight 元素的高度（包括带滚动条的隐蔽的地方）
         */
        function autoScroll(stepLength, speed, delay, element) {
            let interval;
            let step = 1;
            element.scrollTop = 0;

            function start() {
                interval = setInterval(scrolling, speed)
                element.scrollTop += step
            }

            function scrolling() {
                if (element.scrollTop % stepLength !== 0 && element.scrollTop != (element.scrollHeight - element.offsetHeight)) {
                    element.scrollTop += step
                } else {
                    if (element.scrollTop === 0 || element.scrollTop === (element.scrollHeight - element.offsetHeight)) { // 触顶或触底
                        step *= -1 // 转换方向
                    }
                    clearInterval(interval)
                    setTimeout(start, delay)
                }
            }

            if (element.offsetHeight !== element.scrollHeight) { // 元素内容没有溢出时，不触发
                setTimeout(start, delay)
            }
        }

        const elem = document.getElementById('items-list-wrap');
        const stepLength = $('.sigle-item:first-child').height();
        autoScroll(stepLength, 2, 15000, elem);

        // 打印
        $('.printBtn').click(function () {
            // 创建iframe，填入需要打印的内容和样式
            var iframe = document.createElement('IFRAME'),
                doc = null,
                style = ["<style>", "body{font-size: 12px; color: #000;}",".bgRed{background-color: #fd0003;} .bgGray{background-color: #9b9e95;} .bgBlue{background-color: #0095e3;}",
                    ".right-part{display:flex;flex-wrap: wrap;}",
                    ".functional{display:none}",
                    ".sigle-item{text-align: center; border: 1px solid #ccc;}",
                    ".sigle-item p em{margin: 0 5px}",
                    ".meter-img {position: relative;}",
                    ".meter-img img{width: 200px;}",
                    ".meter-img span{position: absolute;top: 42%;left:50%;transform: translateX(-50%);}",
                    "#gl-pie{width: 10px; height:10px}",
                    "##pie-2d:{display:block;}",
                    "#pie-2d, #print-chart{width: 200px; height: 200px}",
                    "</style>"].join(""),
                printHtml = $('#main-wrap').prop("outerHTML");
            iframe.setAttribute("id", "print-iframe");
            iframe.setAttribute('style', 'position:absolute;width:100%;height:100%;left:-100%;top:-100%;z-index:1024;background-color:#fff;');
            document.body.appendChild(iframe);
            doc = iframe.contentWindow.document;
            doc.write(style + printHtml);
            iframe.contentWindow.focus();
            iframe.contentWindow.print();
            iframe.remove();
            $('#printContentBox').empty();
        });

    });
});
